//
//  LXWebView.swift
//  LXReuseTools
//
//  Created by yoctech on 2021/8/11.
//

import UIKit
import WebKit
import LXExtensions

public protocol LXWebViewDelegate: NSObjectProtocol {
    
}

public class LXWebView: UIView {
    public var config: LXWebViewConfig = LXWebViewConfig()
    
    open var url : String?
    
    let userContentController = WKUserContentController.init()
    
    
    lazy var webView: WKWebView = {
        let configuration = WKWebViewConfiguration.init()
        configuration.userContentController = userContentController

        let coll = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewLayout())
        let value = WKWebView.init(frame: .zero, configuration: configuration)
        if #available(iOS 11.0, *) {
            value.scrollView.contentInsetAdjustmentBehavior = .never
        }
        value.navigationDelegate = self
        value.uiDelegate = self
        return value
    }()
    // 进度条
    lazy var progressView:UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = config.progressTintColor
        progress.trackTintColor = config.progressTrackTintColor
        return progress
    }()
    
    func openOutside(_ url: URL) {
        if  UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

    public func getUrlParams(urlStr:String) -> [String:String] {
        var dataDic : [String:String] = [:]

        if urlStr.contains("?") {
            let firstIndex = urlStr.index(after: urlStr.firstIndex(of: "?")!)
            let dataStr = urlStr.substring(from: firstIndex)
            let dataArr = dataStr.components(separatedBy: "&")
            for item in dataArr {
                var itemArr = item.components(separatedBy: "=")
                let key  = itemArr.first!
                itemArr.removeFirst()
                let value : String = itemArr.joined(separator: "=")
                dataDic[key] = value
            }
        }
        return dataDic
    }

}

extension LXWebView :WKNavigationDelegate {
    // 页面开始加载时调用
    public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        /// 获取网页的progress
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = Float(self.webView.estimatedProgress)
        }
        config.navigationDelegate.webView?(webView, didStartProvisionalNavigation: navigation)
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        config.navigationDelegate.webView?(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        config.navigationDelegate.webView?(webView, decidePolicyFor: navigationResponse, decisionHandler: decisionHandler)
    }
        
    // 当内容开始返回时调用
    public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        config.navigationDelegate.webView?(webView, didCommit: navigation)
    }
    // 页面加载完成之后调用
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 1.0
            self.progressView.isHidden = true
        }
        config.navigationDelegate.webView?(webView, didFinish: navigation)

    }
    // 页面加载失败时调用
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 0.0
            self.progressView.isHidden = true
        }
        config.navigationDelegate.webView?(webView, didFail: navigation, withError: error)
    }
}

extension LXWebView: WKUIDelegate {
    public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        config.uiDelegate.webView?(webView, runJavaScriptAlertPanelWithMessage: message, initiatedByFrame: frame, completionHandler: completionHandler)
    }
    
    public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        config.uiDelegate.webView?(webView, runJavaScriptConfirmPanelWithMessage: message, initiatedByFrame: frame, completionHandler: completionHandler)
    }
    
    public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
        config.uiDelegate.webView?(webView, runJavaScriptTextInputPanelWithPrompt: prompt, defaultText: defaultText, initiatedByFrame: frame, completionHandler: completionHandler)
    }
}
extension LXWebView: WKScriptMessageHandler{
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        config.scriptMessageHandler.userContentController(userContentController, didReceive: message)
    }
    
}

